package com.example.service;

import com.example.common.Result;
import com.example.entity.StudyMaterial;
import com.example.mapper.StudyMaterialMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StudyMaterialService {
    @Resource
    private StudyMaterialMapper studyMaterialMapper;

    public Result add(StudyMaterial material) {
        material.setDownloadCount(0);
        material.setStatus(1);
        material.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        studyMaterialMapper.insert(material);
        return Result.success();
    }

    public PageInfo<StudyMaterial> page(StudyMaterial material, Integer pageNum, Integer pageSize, Boolean isAdmin) {
        PageHelper.startPage(pageNum, pageSize);
        List<StudyMaterial> list = studyMaterialMapper.selectAll(material, isAdmin);
        return new PageInfo<>(list);
    }

    public Result changeStatus(Long id, Integer status) {
        StudyMaterial material = studyMaterialMapper.selectById(id);
        if (material == null) {
            return Result.error("资料不存在");
        }
        material.setStatus(status);
        studyMaterialMapper.update(material);
        return Result.success();
    }
    public Result incrementDownload(Long id) {
        StudyMaterial material = studyMaterialMapper.selectById(id);
        if (material == null) {
            return Result.error("资料不存在");
        }
        material.setDownloadCount(material.getDownloadCount() + 1);
        studyMaterialMapper.update(material);
        return Result.success();
    }
}